package com.pig4cloud.pig.pigunit.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.pigunit.entity.Unit;
import com.pig4cloud.pig.pigunit.feign.RemoteBuildingService;
import com.pig4cloud.pig.pigunit.service.UnitService;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springdoc.api.annotations.ParameterObject;

@RestController
@AllArgsConstructor
@RequestMapping("/unit")
@Tag(description = "unit" , name = "单元管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class UnitController {
	private final UnitService unitService;

	@Autowired
	private RemoteBuildingService remoteBuildingService;

	@GetMapping("/page")
	public R getUnitPage(@ParameterObject Page page, @ParameterObject Unit unit){

		return R.ok(unitService.selectAll(page, unit.getUnitName()));
	}

	@GetMapping("/getUnit")
	public R getUnit(@RequestParam("buildingId") Long buildingId){
		QueryWrapper<Unit> wrapper = new QueryWrapper<>();
		wrapper.eq("building_id", buildingId);
		return R.ok(unitService.list(wrapper));
	}

	@GetMapping("/{unitId}")
	public R getById(@PathVariable Long unitId){
		return R.ok(unitService.getById(unitId));
	}

	@PostMapping
	public R save(@RequestBody Unit unit){
		Unit result = unitService.getByBuildingIdAndUnitName(unit);
		if (result != null){
			return R.failed("同一楼宇下，单元名称不能重复");
		}
		return R.ok(unitService.save(unit));
	}
	@PutMapping
	public R updateById(@RequestBody Unit unit){
		Unit result = unitService.getByBuildingIdAndUnitName(unit);
		if (result != null){
			return R.failed("同一楼宇下，单元名称不能重复");
		}
		return R.ok(unitService.updateById(unit));
	}

	@DeleteMapping("/deleteById")
	public R deleteById(@RequestParam Long[] ids) {
		unitService.deleteById(ids);
		return R.ok(null, "删除成功");
	}

	@GetMapping("/getBuilding")
	public R getBuilding() {
		return remoteBuildingService.getAll();
	}


}
